// 适配器类 ： 可以发送 xhr 和 http请求
class Adapter {
  #o2s = (obj) =>
    Object.keys(obj)
      .map((item) => `${item}=${obj[item]}`)
      .join("&");
  xhr(config) {
    // 发送前端的ajax请求；
    return new Promise((resolve) => {
      // console.log("request",this);
      // 发送网络请求
      let {
        url = "",
        params = {},
        data = {},
        method = "get",
        headers = { ["Content-Type"]: "application/json" },
        responseType = "json",
      } = config;

      let xhr = new XMLHttpRequest();
      if (Object.keys(params).length > 0) {
        console.log("this", this);
        url = url + "?" + this.#o2s(params);
      }

      xhr.open(method, url);
      for (let [key, val] of Object.entries(headers)) {
        xhr.setRequestHeader(key, val);
      }

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            let responseObj = {
              config,
              headers: xhr.getAllResponseHeaders(),
              request: xhr,
              status: xhr.status,
              statusText: xhr.statusText,
            };
            if (responseType === "text") {
              responseObj.data = xhr.responseText;
              resolve(responseObj);
            } else if (responseType === "json") {
              responseObj.data = JSON.parse(xhr.responseText);
              resolve(responseObj);
            }
          }
        }
      };

      if (method === "post" || method == "put" || method === "patch") {
        if (headers["Content-Type"] === "application/json") {
          xhr.send(JSON.stringify(data));
        } else {
          xhr.send(this.#o2s(data));
        }
      } else {
        // get delete head  options 形式的ajax；
        xhr.send();
      }
    });
  }
}
export default Adapter;
